#!/usr/bin/env python
# _*_ coding: UTF-8 _*_

def string_split(strvalue, delim, limit = 0):
    """
    Split string
    
    param str: String to be splitted
    param delim: Delimitors
    param limit: Max parts splitted
    """
    
    result = []
    prev = 0
    count = 0
    for i in xrange(len(strvalue)):
        if strvalue[i] in delim:
            if  i > prev:
                result.append(strvalue[prev:i])
                count = count + 1
            prev = i + 1
            if limit and count >= limit:
                break
        i = i + 1
    if prev < len(strvalue):
        result.append(strvalue[prev:])
    return result

def stringr2int(strvalue, keep = False):
    """
    Convert string to integer from right to left
    
    param str: String to be converted
    param keep: When returning keep non-number letters
    """
    
    numbers = "0123456789"
    pos = len(strvalue)
    while pos > 0 and strvalue[pos - 1] in numbers:
        pos = pos - 1
    if pos < len(strvalue):
        number = int(strvalue[pos:])
        remain = strvalue[0:pos]
    else:
        number = None
        remain = strvalue
    return number if not keep else tuple([number, remain])

def stringl2int(strvalue, keep = False):
    """
    Convert string to integer from left to right
    
    param str: String to be converted
    param keep: When returning keep non-number letters
    """
    
    numbers = "0123456789"
    pos = 0
    while pos < len(strvalue) and strvalue[pos] in numbers:
        pos = pos + 1
    if pos > 0:
        number = int(strvalue[0:pos])
        remain = strvalue[pos]
    else:
        number = None
        remain = strvalue
    return number if not keep else tuple([number, remain])

def string_split_pair(strvalue, delim, p1="", p2=""):
    pairs = strvalue.split(delim, 1)
    if len(pairs) == 0:
        pairs = [p1, p2]
    elif len(pairs) == 1:
        pairs.append(p2)
    return (pairs[0], pairs[1])

def uri_parse(uri):
    uri_parts = {"scheme":"", "user":"", "password":"",
        "hostname":"", "port":"", "path":"", 
        "querystring":"", "fragment":""}
    
    pos = uri.find("://")
    if pos >= 0:
        uri_parts["scheme"] = uri[0:pos]
        uri = uri[pos+3:]
    
    host, path = string_split_pair(uri, '/')
    hostpair = host.split('@', 1)
    if len(hostpair) == 1:
        uri_parts["hostname"],uri_parts["port"] = \
            string_split_pair(hostpair[0], ':')
    elif len(hostpair) == 2:
        uri_parts["user"],uri_parts["password"] = \
            string_split_pair(hostpair[0], ':')
        uri_parts["hostname"],uri_parts["port"] = \
            string_split_pair(hostpair[1], ':')

    uri_parts["path"], params = string_split_pair(path, '?')
    uri_parts["querystring"], uri_parts["fragment"] = \
        string_split_pair(params, '#')
    return uri_parts

def cmd_parse(line, delim = " \t\r\n", limit = 0):
    if delim == None:
        delim = " \t\r\n"
    line = line.strip(delim)
    tokens = []
    count = 0
    while line:
        if line[0] == '"' or line[0] == '\'':
            pos = 1
            while pos < len(line) and (line[pos] != line[0] or 
                (line[pos] == line[0] and line[pos-1] == '\\')):
                pos = pos + 1
            if pos == len(line):
                raise SyntaxError("charactor \" or \' not closing")
            tokens.append(line[1:pos])
            count = count + 1
            line = line[pos+1:].strip()
        else:
            pos = 0
            while pos < len(line) and line[pos] not in delim:
                pos = pos + 1
            tokens.append(line[0:pos])
            count = count + 1
            line = line[pos+1:].strip()
        if limit and count >= limit:
            break
    tokens = [token.decode("string-escape") for token in tokens]
    return tokens if not limit else (tokens, line)
